import Vue from "vue";
import Vuex from "vuex";
import lodash from "lodash";
import { asyncRoutes, constantRoutes } from "@router/index";

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        routers: constantRoutes, // 总路由
        addRouters: [], // 新增路由
        isMobile: browserRedirect(),
        navStatusBol: !browserRedirect(),
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers;
            state.routers = constantRoutes.concat(routers);
        },

        SET_NAV: (state, status) => {
            state.navStatusBol = status;
        },
    },
    actions: {
        GenerateRoutes({ commit }, data) {
            return new Promise((resolve) => {
                const { roles } = data,
                    routes = lodash.cloneDeep(asyncRoutes), // 深拷贝，防止重新登录丢失路由部分结构
                    accessedRouters = rolePermission(roles, routes);
                commit("SET_ROUTERS", accessedRouters);
                resolve();
            });
        },
    },
    getters: {},
    modules: {},
});

/**
 * @description 过滤路由权限
 */
function rolePermission(roles, routes) {
    return routes.filter((value) => {
        if (roles.indexOf("admin") >= 0) {
            return true;
        }
        if (hasPermission(roles, value)) {
            if (value.children?.length > 0) {
                value.children = rolePermission(roles, value.children); // 递归子路由
                value.redirect = value.children[0].path; // 修改当前重定向为子路由第一个path
            }
            return value;
        }
        return false;
    });
}

/**
 * @description 匹配当前路由是否有权限
 */
function hasPermission(roles, route) {
    if (route.meta?.roles) {
        return roles.some((role) => route.meta.roles.indexOf(role) >= 0);
    }
    return true;
}

function browserRedirect() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphone = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "web";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    if (
        bIsIpad ||
        bIsIphone ||
        bIsMidp ||
        bIsUc7 ||
        bIsUc ||
        bIsCE ||
        bIsWM ||
        bIsAndroid
    ) {
        return true;
    }
    return false;
}
